#include "CustomExport.h"

void CustomExport::write(string outputName, string outputType, sc_object* top)
{
	mOutputType = outputType;
	mOutputName = outputName;

	XMLExport::write(INTERMEDIATE_OUTPUT_NAME, top);
}

void CustomExport::generateOutput(string outputName)
{
	string filePath = string(getenv(ROOT_DIR)).append("Settings\\");
	TiXmlDocument settings( filePath.append("ExportSettings.xml").c_str() );
	settings.LoadFile();
	TiXmlElement* outputType = settings.FirstChildElement("ExportSettings")->FirstChildElement("OutputTypeList")->FirstChildElement();
	string name, xsl, fileExtension;
	while (outputType)
	{
		TiXmlAttribute* attribute = outputType->FirstAttribute();
		while (attribute)
		{
			if (string(attribute->Name()) == "name") name = attribute->Value();
			else if (string(attribute->Name()) == "xsl") xsl = attribute->Value();
			else if (string(attribute->Name()) == "fileExtension") fileExtension = attribute->Value();
			attribute = attribute->Next();
		}
		if (name == mOutputType) break;
		outputType = outputType->NextSiblingElement();
	}
	if (name == mOutputType)
	{
		XMLExport::generateOutput(outputName);
		TiXmlElement* processor = settings.FirstChildElement("ExportSettings")->FirstChildElement("XSLT_Processor");

		string command = processor->GetText();
		command.replace(command.find("[input]"), 7, string(INTERMEDIATE_OUTPUT_NAME).append(".xml"));
		command.replace(command.find("[xsl]"), 5, xsl);
		command.replace(command.find("[output]"), 8, string(mOutputName).append(".").append(fileExtension));
		system(command.c_str());


	}
	else
	{
		cout << "Error: output format '" << mOutputName << "' unknown";
	}
}

